import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { DatePicker } from 'antd-mobile';

export const dateFormat = function convertDate(date, format) {
    let str = format;
    let o = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    if (/(Y+)/.test(format)) {
        str = str.replace(RegExp.$1, date.getFullYear().toString().substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
            str = str.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(o[k].toString().length));
        }
    }
    return str;
}

export const yearAndMonth = function calcYearMonth(date) {
    if (date === null || date === undefined) {
        return ""
    }
    let array = date.split("-")
    let months = (new Date().getFullYear() - parseInt(array[0], 10)) * 12 + (new Date().getMonth() + 1 - parseInt(array[1], 10))

    let month = months % 12
    return (parseInt(months / 12, 10)) + '岁' + (month === 0 ? '' : month + '个月')
}


// 日期选择
class BrithdayPicker extends Component {

    constructor(props, context) {
        super(props, context);
        let date = new Date()
        if (this.props.date) {
            date = new Date(Date.parse(this.props.date.replace(/-/g, "/")));
        }
        this.state = {
            isOpen: this.props.isOpen,
            date: date
        }
    }

    componentWillReceiveProps(nextProps, nextState) {
        this.setState({
            isOpen: nextProps.isOpen,
        });
    }

    handleCancel = () => {
        this.setState({ isOpen: false });
        this.props.dismiss()
    }

    handleSelect = (time) => {
        this.props.submit({ value: dateFormat(time, 'YYYY-MM-DD') })
        this.setState({ isOpen: false });
    }
    render() {
        return (
            <DatePicker
                mode="date"
                maxDate={new Date()}
                minDate={new Date('1918-01-01')}
                title="日期选择"
                visible={this.state.isOpen}
                value={this.state.date}
                onOk={date => this.handleSelect(date)}
                onDismiss={this.handleCancel}
            />
        )
    }
}

BrithdayPicker.propTypes = {
    dismiss: PropTypes.func.isRequired,
    submit: PropTypes.func.isRequired,
};

export default BrithdayPicker;